from django.db.models import Q
from models import Asset

from tags.models import TaggedObject

def searchAssets(request):  
  start = request.GET.get('start', 0)
  end = request.GET.get('end', None)
  since = request.GET.get('since', None)
  sinceord = request.GET.get('sinceord', 'asc')
  username = request.GET.get('user', None)
  
  search =  request.GET.get('search', '')
  tags =  request.GET.getlist('tags')
  formats = request.GET.getlist('formats')
  formattypes = request.GET.getlist('formattypes')
  collections =  request.GET.getlist('collections')
  print "SEARCH:", search, tags, formats, collections
  
  assets = Asset.objects
  
  if username:
    assets = assets.filter(file__author__username__iexact=username)
  
  assets = assets.filter(Q(subName__icontains=search) | Q(file__file_name__icontains=search))
  
  if len(tags) > 0:
    items = TaggedObject.objects.filter(tag__id__in=tags).values_list('object_id', flat=True)  
    print 'GA', items
    assets = assets.filter(pk__in=items)  
   
  if len(formats) > 0:
    assets = assets.filter(format__in=formats)
    
  if len(formattypes) > 0:
    assets = assets.filter(format__type__in=formattypes)
      
  if len(collections) > 0:
    assets = assets.filter(collection__id__in=collections)
  
  if since:
    assets = assets.filter(stamp__gte=since)
    assets = assets.order_by('stamp' if sinceord == 'asc' else '-stamp')
  
  assets = assets.distinct()
  total = assets.count()
  assets = assets[start:end]
  print 'R', assets, total
  return assets, total
